import {URL} from "./../libs/Url";
import {Fetch, MD5} from "./../libs/";
import {
    FETCH_USER_REQUEST,
    FETCH_USER_RECEIVE,
    TOGGLE_MENU,
    SELECT_NOTICE_LIST,
    FETCH_ACTION_REQUEST,
    FETCH_ACTION_RECEIVE,
    FETCH_ACTION_REMOVE_REQUEST,
    FETCH_ACTION_REMOVED_RECEIVE,
    FETCH_USER_CLASS_SELECT,
    SET_FORM_ITEM,
    ENABLE_DELETE_BTN,
    SELECT_ALL_ITEM,
    SELECT_ITEM,
    OPEN_MODAL,
    CLOSE_MODAL,
    SET_ARGUMENT_ITEM,
    UPDATE_ITEM_FOR_LIST_BY_INDEX,
    ADD_ITEM_TO_LIST, SET_DEFAULT_USER
} from "./../actionsType";
// import {getUrlBySubject} from "./subject";

export function setDefaultUser(user) {
    return {
        type: SET_DEFAULT_USER,
        user
    }
}
/*
 * action 创建函数
 */
export function toggleMenu(text) {
    return {type: TOGGLE_MENU, text}
}
export function update_item_for_list_by_index(subject, item, index) {
    return {type: UPDATE_ITEM_FOR_LIST_BY_INDEX, item, index, subject}
}
export function add_item_to_list(subject, item) {
    return {type: ADD_ITEM_TO_LIST, item, subject}
}
export function selectMenuItem(text) {
    return {type: TOGGLE_MENU, text}
}
export function setArgumentItem(subject, query) {

    return {type: SET_ARGUMENT_ITEM, subject, query}
}


function request_user(keyword) {
    return {
        type: FETCH_USER_REQUEST,
        keyword,
    }
}
/***
 *
 * @param index
 * @returns {{type, index: *}}
 */
export function select_user_class(index) {
    return {
        type: FETCH_USER_CLASS_SELECT,
        index
    }
}
function receive_user(user) {
    return {
        type: FETCH_USER_RECEIVE,
        user,
        receivedAt: Date.now()
    }
}

export function selectRequest(subject) {
    return {
        type: SELECT_NOTICE_LIST,
        subject,
    }
}

export function setFormItem(subject, formItem) {
    return {
        type: SET_FORM_ITEM,
        subject,
        item: formItem
    }
}
/**
 * should fetch logined user
 */
function shouldFetch(state, keyword) {
    const user = state.user_login.user;
    if (_.isEmpty(user)) {
        return true
    } else {
        return false
    }
}

function fetchUser_() {
    return dispatch => {
        dispatch(request_user());
        return Promise.all([Fetch(URL.Get_USER), Fetch(URL.Get_USER_CLASS)])
            .then(json => {
                const user = json[0].user || {};
                user.class = json[1].list;
                user.isheadteacher = json[0].isheadteacher == 'true' ? true : false;
                var tmp_index = -1;
                json[1].headteacherclass && ( user.dutyClass = json[1].headteacherclass);
                if (json[1].headteacherclassid) {
                    user.class.map((item, index)=> {
                        if (item['class'].classid == json[1].headteacherclassid) {
                            tmp_index = index;
                        }
                    });
                    if (tmp_index > -1)
                        user.dutyClass = user['class'][tmp_index];
                }
                json[1].headteacherclassid && ( user.headteacherclassid = json[1].headteacherclassid);

                dispatch(setDefaultUser(user));
                return dispatch(receive_user(user));
            })
            .catch(e=> {
                dispatch(setDefaultUser({}));
                console.log(e)
            })
    }
}
function shouldFetchUser(state, subject) {
    const subject_ = state.user.user;
    if (!subject_.class.length && !state.user.isFetching) {
        return true
    } else {
        return false
    }
}
/***
 *  fetch login user
 */
export function fetchUser() {
    return (dispatch, getState) => {
        if (shouldFetchUser(getState())) {
            return dispatch(fetchUser_())
        }
    }
}

////common logic begin


/**
 * request fetch
 * @returns {{type}}
 */
function request_fetch(subject) {
    return {
        type: FETCH_ACTION_REQUEST,
        subject
    }
}
/**
 * receive fetch
 * @returns {{type}}
 */
function receive_fetch(subject, json, query) {
    return {
        type: FETCH_ACTION_RECEIVE,
        subject,
        json,
        query,
        receivedAt: Date.now()
    }
}
/**
 * should fetch subject
 */
function shouldFetch(state, subject, query) {
    const subject_ = state.fetchBySubject[subject];
    query.POST && (delete query.POST);
    /**
     * 请求必要条件
     * 1. 没有缓存数据
     * 2. 条件跟之前不一致
     * 3. 没有正在请求
     */
    if (!subject_ || ((!subject_.retCode || !subject_.query || MD5(JSON.stringify(query)) != MD5(JSON.stringify(subject_.query)))
        && !subject_.isFetching)) {

        // if (
        // (!subject_.list.length ||
        // (subject_.list.length && query.keyword != subject_.keyword) ||
        // query.currentPage != subject_.page)
        // && !subject_.isFetching) {
        return true
    } else {
        return false
    }
}
/**
 * fetch action
 * @param subject
 * @returns {function(*)}
 */
function fetch_action(subject, query, state) {
    return dispatch => {
        dispatch(request_fetch(subject))
        // query = Object.assign({}, state.fetchBySubject[subject].query, query);
        let fetch_res = state.fetchBySubject[subject];
        query = Object.assign({}, fetch_res ? (fetch_res.query || {}) : {}, query);
        return Fetch(query.url, Object.assign({body: query}, query.POST ? {method: 'POST'} : {}))
            .then(json => {
                return dispatch(receive_fetch(subject, json, query));
            })
            .catch(e => {
                console.log(e);
                alert(e);
            })
    }
}
/***
 *  fetch subject async
 */
export function fetch(query = {}) {
    return (dispatch, getState) => {
        if (!query.url)throw new Error('argument invalid !');
        let post = query.POST ? true : false;
        const subject = MD5(query.url.slice(0, query.url.indexOf('?')));
        var judge = shouldFetch(getState(), subject, query);

        if (judge) {
            query['POST'] = post;
            return dispatch(fetch_action(subject, query, getState()))
        }
    }
}


function request_fetch_remove_request(subject) {
    return {
        type: FETCH_ACTION_REMOVE_REQUEST,
        subject,
    }
};

function request_fetch_removed_receive(subject, json, query) {
    return Object.assign({}, {
        type: FETCH_ACTION_REMOVED_RECEIVE,
        subject,
        json,
        ...query,
    }, query.target ? {target: query.target} : {})
}

function fetch_remove_action(subject, query) {
    return dispatch => {
        dispatch(request_fetch_remove_request(subject))
        return Fetch(query.url, {body: query})
            .then(json => {
                return dispatch(request_fetch_removed_receive(subject, json, query));
            })
            .catch(e => {
                console.log(e);
                alert(e);
            });
    }
}
export function fetch_remove(query = {}) {
    const subject = MD5(query.url.slice(0, query.url.indexOf('?')));
    return (dispatch, getState) => {
        dispatch(fetch_remove_action(subject, query))
    }
}


export function enable_delete_btn(subject, text) {
    return {type: ENABLE_DELETE_BTN, ...text, subject}
}


/**
 * flag : true | false
 * @param flag
 */
export function selectAllItem(subject, flag) {
    return {
        type: SELECT_ALL_ITEM,
        subject,
        flag
    }
}

/***
 * combine action
 */
export function selectItem(subject, index) {
    return dispatch=> {
        dispatch(select_(subject, index))
    }
}
export function select_(subject, index) {
    return {
        type: SELECT_ITEM,
        ...index,
        subject
    }
}

export function openModal(subject) {
    return {
        type: OPEN_MODAL,
        subject
    }
}
export function closeModal(subject) {
    return {
        type: CLOSE_MODAL,
        subject
    }
}